package com.company;

import org.apache.commons.codec.digest.DigestUtils;

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @date : 2023/2/1 09:47
 * https://www.mscs.dal.ca/~selinger/md5collision/
 * MD5 Collision
 * 两个字符串转成的字节数组碰撞例子
 */

public class P040_MD5Collision {

    public static void main(String[] args) {
        String s1 = "d131dd02c5e6eec4 693d9a0698aff95c 2fcab58712467eab 4004583eb8fb7f89" +
                "55ad340609f4b302 83e488832571415a 085125e8f7cdc99f d91dbdf280373c5b" +
                "d8823e3156348f5b ae6dacd436c919c6 dd53e2b487da03fd 02396306d248cda0" +
                "e99f33420f577ee8 ce54b67080a80d1e c69821bcb6a88393 96f9652b6ff72a70";

        String s2 = "d131dd02c5e6eec4 693d9a0698aff95c 2fcab50712467eab 4004583eb8fb7f89" +
                "55ad340609f4b302 83e4888325f1415a 085125e8f7cdc99f d91dbd7280373c5b" +
                "d8823e3156348f5b ae6dacd436c919c6 dd53e23487da03fd 02396306d248cda0" +
                "e99f33420f577ee8 ce54b67080280d1e c69821bcb6a88393 96f965ab6ff72a70";
        System.out.println(s1.compareTo(s2));
        System.out.println(md5(strToHex(s1)).equals(md5(strToHex(s2))));
        System.out.println(md5(strToHex(s1)));
        System.out.println(md5(strToHex(s2)));
    }

    private static String md5(String filename) {
        try (InputStream inputStream = Files.newInputStream(Paths.get(filename))) {
            return DigestUtils.md5Hex(inputStream);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String md5(byte[] bytes) {
        return DigestUtils.md5Hex(bytes);
    }

    public static byte[] strToHex(String s) {
        s = s.replace(" ", "");
        byte[] ans = new byte[s.length() / 2];
        String hexDigits = "0123456789abcdef";
        for (int i = 0; i < ans.length; i++) {
            int pos = i * 2;
            int h = hexDigits.indexOf(s.charAt(pos)) << 4;
            int l = hexDigits.indexOf(s.charAt(pos + 1));
            ans[i] = (byte) (h | l);
        }
        return ans;
    }
}
